import React, { createContext, useContext, useState, useRef } from 'react';

export interface TableSelection {
  row: number;
  col: number;
  value?: any;
}

export interface ExcelTableContextType {
  fileName: string;
  setFileName: (name: string) => void;
  selection: TableSelection[]; // 当前选区的所有单元格
  setSelection: (selection: TableSelection[]) => void;
  getSelection: () => TableSelection[];
  setCellValue: (row: number, col: number, value: any) => void;
  getCellValue: (row: number, col: number) => any;
  tableList: any[][];
  setTableData: (data: any[][]) => void;
}

const ExcelTableContext = createContext<ExcelTableContextType | null>(null);

export const useExcelTable = () => {
  const ctx = useContext(ExcelTableContext);
  if (!ctx) throw new Error('useExcelTable must be used within ExcelTableProvider');
  return ctx;
};

export const ExcelTableProvider: React.FC<{children: React.ReactNode}> = ({ children }) => {
  const [fileName, setFileName] = useState<string>('未命名文档');
  const [selection, setSelection] = useState<TableSelection[]>([]);
  const [tableList, setTableData] = useState<any[][]>([]);

  // 获取当前选区
  const getSelection = () => selection;

  // 设置单元格内容
  const setCellValue = (row: number, col: number, value: any) => {
    setTableData(prev => {
      const newData = prev.map(arr => [...arr]);
      if (!newData[row]) newData[row] = [];
      newData[row][col] = value;
      return newData;
    });
  };

  // 获取单元格内容
  const getCellValue = (row: number, col: number) => {
    return tableList[row]?.[col];
  };

  return (
    <ExcelTableContext.Provider
      value={{
        fileName,
        setFileName,
        selection,
        setSelection,
        getSelection,
        setCellValue,
        getCellValue,
        tableList,
        setTableData,
      }}
    >
      {children}
    </ExcelTableContext.Provider>
  );
};